import React, {PureComponent} from 'react'
import {View, SectionList, Text, Image,UIManager,findNodeHandle, Dimensions,TouchableOpacity, StyleSheet,SafeAreaView, Animated,DeviceEventEmitter} from 'react-native'

import DetailHeaderView from '../../widget/detail/DetailHeaderView'
import {ImageButton} from "../../widget/CustomButton";
import DetailTeacherCell from '../../widget/detail/DetailTeacherCell'
import DetailCommentCell from '../../widget/detail/DetailCommentCell'
import DetailLessonCell from '../../widget/detail/DetailLessonCell'
import DetailCommentMoreCell from '../../widget/detail/DetailCommentMoreCell'
import DetailNavigation from '../../widget/detail/DetailNavigation'
import DetailfreeBottom from '../../widget/detail/DetailfreeBottom'
import DetailBuyBottom from '../../widget/detail/DetailBuyBottom'

import {SpaceView} from '../../widget/Separator'
import CommentListScene from "../comment/CommentListScene";
import color from "../../widget/color";
import method  from '../../api/method'
import api  from '../../api/api'
import {fetchGetRequest,fetchPostRequest}  from '../../api/NetworkTool'
// import Toast, {DURATION} from 'react-native-easy-toast'
import DetailTopTabBar from '../../widget/detail/DetailTopTabBar'
import DeviceStorage from "../../utils/DeviceStorage";
import define from "../../utils/define";

import Tips from 'react-native-root-tips'
import NetTool from "../../api/NetTool";
import HTML from 'react-native-render-html';
import {NavigationActions} from "react-navigation";
import {Tip} from "../../widget/Text";
import CommonAlertDialog from '../../widget/dialog/CommonAlertDialog'

const {width} = Dimensions.get('window')

const screenWidth = Dimensions.get('window').width

type Props = {
    navigation:any,
}

export default class CourseDetailScene extends PureComponent<Props> {
    static navigationOptions = ({navigation}) => ({
        headerTintColor:'#333333',
        headerStyle:{backgroundColor:'white'},
        title:'课程详情',
        headerRight:<Text/>,
        headerLeft:<TouchableOpacity onPress={()=>{
            navigation.goBack()
        }}>
            <Image style={{marginLeft:12}} source={require('../../../res/img/gobal_back.png')}/>
        </TouchableOpacity>
    });

    constructor(props) {
        super(props)
        this.state = {
            image_height:0,
            top_show:false,
            top_index:0,
            // is_buy:false,
            sections: [
                {
                    data: [],
                    key: '111', renderItem: this._renderItemCourseComponent
                },
                {
                    data: [],
                    key: '222', renderItem: this._renderItemTeacherComponent
                },

            ],
            detail:{
                discounts:[{
                    id:0,
                    course_id:0,
                    discount:0,
                    start_at:'',
                    end_at:'',
                    deleted_at:null,
                }],
                is_buy:0,
                id:0,
                title:'',
                start_date:'',
                remains:0,
                buy_num:0,
                price:'',
                lessons:[],
                teacher:[{name:''},{name:''}],
                end_date:'',
                start_date:'',
            },
            show_alert:false,
            headerHeight:0,
        }
    }

    componentDidMount() {


        const {info} = this.props.navigation.state.params
        let params = {
            courseId:info.id,
        }
        fetchGetRequest(api.getCourse,method.get,params)
            .then(res=>{
                console.log('open',res)
                if(res.introduce_image){
                    this.setState({sections:
                            [
                                {
                                    data: [res.introduce_image],
                                    key: '111', renderItem: this._renderItemCourseComponent
                                },

                                {
                                    data: res.lessons,
                                    key: '222', renderItem: this._renderItemLessonComponent
                                },
                                {
                                    data: res.teacher,
                                    key: '333', renderItem: this._renderItemTeacherComponent
                                },

                            ]
                    })
                }else {
                    this.setState({sections:
                            [
                                {
                                    data: [res.course_detail],
                                    key: '111', renderItem: this._renderItemCourseTextComponent
                                },

                                {
                                    data: res.lessons,
                                    key: '222', renderItem: this._renderItemLessonComponent
                                },
                                {
                                    data: res.teacher,
                                    key: '333', renderItem: this._renderItemTeacherComponent
                                },

                            ]
                    })
                }

                this.setState({detail:res})

            })
            .catch(err=>{
                Tips.showWarn(err,{mask:true})
            })

    }
    pushCourseOrder(){

        const {info} = this.props.navigation.state.params
        let proudId = '[(' + info.id + ',0' + ')]'
        let params = {
            productId:proudId,
        }
        DeviceStorage.get(define.token)
            .then(res=>{
                if (res){

                    fetchGetRequest(api.findUnpaidOrder, method.get, {course_id:info.id})
                        .then(res=>{
                            if (res){
                                fetchGetRequest(api.queryPay, method.get, {orderSn:res.order_sn})
                                    .then(res=>{
                                        if (res.status == 'unpaid'){
                                            this.setState({show_alert:true})
                                        }else {
                                            fetchPostRequest(api.createOrder,method.post,params)
                                                .then(res=>{
                                                    this.props.navigation.navigate("CourseOrderScene",{course:res.course[0],address:res.address,order:res.order})
                                                })
                                                .catch(err=>{
                                                    Tips.showInfo(err,{mask:true})
                                                })
                                        }
                                    })
                                    .catch(err=>{
                                        Tips.showInfo(err,{mask:true})
                                    })
                            }
                        })
                        .catch(err=>{
                            if (err == '无法获取当前未支付订单信息') {
                                fetchPostRequest(api.createOrder,method.post,params)
                                    .then(res=>{
                                        this.props.navigation.navigate("CourseOrderScene",{course:res.course[0],address:res.address,order:res.order})
                                    })
                                    .catch(err=>{
                                        Tips.showInfo(err,{mask:true})
                                    })
                            }


                        })
                    // fetchPostRequest(api.createOrder,method.post,params)
                    //     .then(res=>{
                    //         this.props.navigation.navigate("CourseOrderScene",{course:res.course[0],address:res.address,order:res.order})
                    //     })
                    //     .catch(err=>{
                    //         Tips.showInfo(err,{mask:true})
                    //     })
                }else {
                    Tips.showWarn('请先登录',{mask:true})
                }
            }).catch(err=>{
        })

    }

    jumpShop(){
        this.props.navigation.navigate('ShoppingCart')
    }

    joinShop(){
        const {info} = this.props.navigation.state.params
        let params = {
            course:info.id,
        }
        DeviceStorage.get(define.token)
            .then(res=>{
                if (res){

                    fetchGetRequest(api.findUnpaidOrder, method.get, {course_id:info.id})
                        .then(res=>{
                            if (res){
                                fetchGetRequest(api.queryPay, method.get, {orderSn:res.order_sn})
                                    .then(res=>{
                                        if (res.status == 'unpaid'){
                                            this.setState({show_alert:true})
                                        }else {
                                            fetchGetRequest(api.join_shop,method.get,params)
                                                .then(res=>{
                                                    Tips.showSuccess('加入购物车成功',{mask:true})
                                                })
                                                .catch(err=>{
                                                    Tips.showInfo(err,{mask:true})
                                                })
                                        }
                                    })
                                    .catch(err=>{
                                        Tips.showInfo(err,{mask:true})
                                    })
                            }
                        })
                        .catch(err=>{
                            if (err == '无法获取当前未支付订单信息') {
                                fetchGetRequest(api.join_shop, method.get, params)
                                    .then(res => {
                                        Tips.showSuccess('加入购物车成功', {mask: true})
                                    })
                                    .catch(err => {
                                        Tips.showInfo(err, {mask: true})
                                    })
                            }
                        })
                    // fetchGetRequest(api.join_shop,method.get,params)
                    //     .then(res=>{
                    //         Tips.showSuccess('加入购物车成功',{mask:true})
                    //     })
                    //     .catch(err=>{
                    //         Tips.showInfo(err,{mask:true})
                    //     })
                }else {
                    Tips.showWarn('请先登录',{mask:true})
                }
            }).catch(err=>{
        })

    }


    freeAndGood() {
        const {type,info} = this.props.navigation.state.params

        if (type > 0) {
            return <DetailfreeBottom  detail={this.state.detail} callbackBoMing={()=>{
                DeviceStorage.get(define.token)
                    .then(res=>{
                        if (res){
                            let params = {
                                courseId:info.id,
                            }
                            fetchPostRequest(api.joinCourse,method.post,params)
                                .then(res=>{
                                    Tips.showSuccess('报名成功',{mask:true})
                                    this.props.navigation.goBack()
                                    DeviceEventEmitter.emit('buySuccess', res.profile);

                                })
                                .catch(err=>{})
                        }else {
                            Tips.showWarn('请先登录',{mask:true})
                        }
                    }).catch(err=>{
                })
            }}/>
        } else {
            return <DetailBuyBottom   detail={this.state.detail} jumpShop={()=>{this.jumpShop()}} joinShop={()=>{this.joinShop()}} callbackBoMing={()=>{this.pushCourseOrder()}}/>
        }
    }

    _listHeader() {
        return <DetailHeaderView detail={this.state.detail} callBackheight={(height)=>{
            this.setState({headerHeight:height})
        }}/>
    }

    _extraUniqueKey = (item, index) => {
        return index + item;
    };
    _renderItemCourseTextComponent = ({item}) => {

        return (<View style={{paddingLeft:12,paddingRight:12,paddingBottom:20}} key={item}>
            <HTML html={item} imagesMaxWidth={(width-24)}/>
        </View>)
    }
    _renderItemCourseComponent = ({item}) => {
        Image.getSize(item,(width,height) => {
            //width 图片的宽度
            //height 图片的高度
            let myHeight = Math.floor((screenWidth-20)/width*height);
            this.setState({image_height:myHeight})
        })
        return (<View style={{alignItems:'center'}} key={item}>
            <Image style={{width:(width - 20),height:this.state.image_height}} source={{uri:item}}/>
        </View>)
    }
    _renderItemTeacherComponent = ({item}) => {
        return <DetailTeacherCell onPress={()=>{
            this.props.navigation.navigate('teacherHomeScene',{teacher_id:item.id})
        }} info={item} key={item.id}/>
    }
    _renderItemLessonComponent = (item) => {
        return <DetailLessonCell info={item.item} key={item.item.id} index={item.index}/>
    }
    _commentMore(){

    }
    _renderItemCommentComponent = ({item}) => {
        if (item.type) {
            return <DetailCommentMoreCell key={item.id} onPress={()=>{this._commentMore()}}/>
        } else {
            return <DetailCommentCell info={item} key={item.id}/>
        }
    }

    renderHeader = ({section}) => {
        if (section.key == '111'){
            return <DetailTopTabBar activeTab={this.state.top_index} tabNames={['课程介绍','课程大纲','老师介绍',]} tabs={['课程介绍','课程大纲','老师介绍',]} goToPage={(i)=>{
                this.setState({top_index:i})
                if(i == 0){
                    this.section_list.scrollToLocation({
                        sectionIndex:i,
                        itemIndex:0,
                        viewOffset:this.state.headerHeight + 72,
                    })
                }else {
                    this.section_list.scrollToLocation({
                        sectionIndex:i,
                        itemIndex:0,
                        viewOffset:0,
                    })
                }
            }}/>
        }
        else if (section.key == '333') {
            return (
                <View style={{backgroundColor:'white'}}  ref={(e)=>{this.teacher_section = e;}}>
                    <SpaceView/>
                    <View>
                        <Text style={styles.header_text}>老师介绍</Text>
                    </View>
                </View>
            )
        }
        else {
            return (
                <View style={{backgroundColor:'white'}} ref='comment_section'>
                    <SpaceView/>
                    <View style={styles.header_comment_view}>
                        <View style={{flexDirection:'row',alignItems:'center'}}>
                            <Text style={styles.header_text}>课程大纲</Text>
                            <Text style={{color:'rgba(0,0,0,0.5)',fontSize:12,marginLeft:11}}>(共{section.data.length}节)</Text>
                        </View>
                    </View>
                </View>
            )
        }


    }


    render() {

        return (
            <SafeAreaView style={{flex:1,backgroundColor:'white'}}>
                {this._renderTopTabBar(this.state.top_show)}
                <SectionList
                    onMomentumScrollEnd={this._contentViewScroll}
                    onScroll={(e)=>{this._onScroll(e)}}
                    stickySectionHeadersEnabled={false}
                    ref={(e) =>{this.section_list = e;}}
                    ListHeaderComponent={this._listHeader()}
                    keyExtractor={this._extraUniqueKey}
                    renderSectionHeader={this.renderHeader}
                    sections={this.state.sections}
                />
                <CommonAlertDialog show={this.state.show_alert} title={'该课程已生成订单！'} onPress={()=>{
                    this.props.navigation.navigate('MineOrderScene',{number:1})
                }} closeModal={(st)=>{
                    this.setState({show_alert:st})
                }} confirmTitle={'去支付'}/>
                {this.freeAndGood()}

            </SafeAreaView>
        )
    }
    // showMeasure = () =>{
    //     this.refs.comment_section.measure((x,y,width,height,px,py) =>
    //         alert(py)
    //     );
    // }
    _contentViewScroll(e:Object){
        var offsetY = e.nativeEvent.contentOffset.y; //滑动距离
        console.log(offsetY)
        // if(this.state.top_index == 0){
        //     this.setState({contentOffsetY1:offsetY})
        // }else if(this.state.top_index == 1){
        //     this.setState({contentOffsetY2:offsetY})
        // }else if(this.state.top_index == 2){
        //     this.setState({contentOffsetY3:offsetY})
        // }


    }
    _renderTopTabBar(is){
        if (is){
            return <DetailTopTabBar style={{position:'absolute'}} activeTab={this.state.top_index} tabNames={['课程介绍','课程大纲','老师介绍',]} tabs={['课程介绍','课程大纲','老师介绍',]} goToPage={(i)=>{
                this.setState({top_index:i})
                if(i == 0){
                    this.section_list.scrollToLocation({
                        sectionIndex:i,
                        itemIndex:0,
                        viewOffset:this.state.headerHeight + 72,
                    })
                }else {
                    this.section_list.scrollToLocation({
                        sectionIndex:i,
                        itemIndex:0,
                        viewOffset:0,
                    })
                }
            }}/>
        }else{
            return <View/>
        }
    }
    _onScroll(e) {
        var offsetY = e.nativeEvent.contentOffset.y; //滑动距离
        if (offsetY > this.state.headerHeight){
            this.setState({top_show:true})
        }else{
            this.setState({top_show:false})
        }
        // if (offsetY >= this.state.contentOffsetY3){
        //    this.setState({top_index:2})
        // }else if (offsetY >= this.state.contentOffsetY2 && offsetY < this.state.contentOffsetY3){
        //     this.setState({top_index:1})
        // }else if(offsetY >= this.state.contentOffsetY1 && offsetY < this.state.contentOffsetY2){
        //     this.setState({top_index:0})
        // }
    }
}
const styles = StyleSheet.create({
    header_title: {
        color: 'rgba(0,0,0,0.7)',
        fontSize: 15,
    },
    header_view: {
        flexDirection: 'row',
        // justifyContent:'space-around',
        height: 54,
        backgroundColor: 'white',
        alignItems: 'center',
    },
    header_select_title: {
        color: 'rgb(0,0,0)',
        fontSize: 15,
        fontWeight: 'bold',
        marginLeft: 12,
    },
    header_text: {
        color: 'black',
        fontSize: 16,
        marginLeft: 12,
        marginTop: 20,
        marginBottom: 20,
        fontWeight: '900',
    },
    header_comment_view: {
        width: width,
        height: 45,
        backgroundColor: 'white',
    },
    list: {
        //justifyContent: 'space-around',
        flexDirection: 'row',//设置横向布局
        flexWrap: 'wrap',  //设置换行显示
        alignItems: 'flex-start',
        backgroundColor: '#FFFFFF'
    },
})